"""
-------------------------------------------------
        同目录调用方法
        # -*- coding: utf-8 -*-
    from viptool_ini import *

   File Name：     viptool
   Description :   used for init request needs parms
   用于提供给request方便维护的header 和cookies
   header 可以有随机ua
   Author :        shenhuawade
   date：          2019/7/23
-------------------------------------------------
-------------------------------------------------
"""
import json
import os
import random

import re
from lxml import etree

import requests
import time

from constants import logger
from fake_useragent import UserAgent # 获取随机useragent
import logging
from logging.handlers import RotatingFileHandler

ua = UserAgent().random
header = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Cookie": "ABTEST=2|1561358499|v1; IPLOC=CN1100; SUID=1A4FC17C4631990A000000005D1070A3; SUV=00CDEE0D7CC14F1A5D1070A35DFF7862; SUID=1A4FC17C2113940A000000005D1070A3; weixinIndexVisited=1; pgv_pvi=2997798912; ld=tZllllllll2N9tTHlllllV1S8k7lllllKGV5pklllltlllllpylll5@@@@@@@@@@; LSTMV=682%2C416; LCLKINT=8742; SNUID=F7A22C91EDE961A343DEFB22EDD4F97E; sct=14; JSESSIONID=aaaoA1hhCs7Mf8ji7bsTw",
    "Host": "weixin.sogou.com",
    "Pragma": "no-cache",
    "Referer": "https://weixin.sogou.com/weixin?usip=&query=%E9%98%BF%E5%B0%94%E6%B3%95%E7%8B%97&ft=&tsn=1&et=&interation=&type=2&wxid=&page=2&ie=utf8",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
}

#匹配目标公众号
def matchGZH(content, keyword):
    abc = fr'<em><!--red_beg-->{keyword}<!--red_end--></em></a>'
    # print(content)
    myvalue = re.search(abc,content,re.IGNORECASE)
    print(myvalue)
    if myvalue == None:
        # 丢弃
        # print(f'公众号没找到{keyword}')
        return False
    else:
        #匹配到公众号
        # print(f'公众号-------{keyword}')
        return True
#匹配目标微信
def matchwx(content, keyword):
    #进来的微信词语获得一下对应的公众号名，有名字的匹配下公众号
    def etreeParse(content):
        try:
            ehtml = etree.HTML(content)
            #找到对应的公众号
            searchlist = ehtml.xpath('//*[@id="sogou_vr_11002301_box_0"]/div/div[2]/p[1]/a/text()')
            print('searchlist内容是-------------')
            print(searchlist)
            return searchlist[0]
        except:
            pass
    try:
        wx_gzh = etreeParse(content)   #获得微信号对应的公众号名称
        vip.writetxt(str(wx_gzh),'可能用上的词语.txt')
    except Exception as e:
        print(e)
        pass
    abc = fr'<p class="info">微信号：<label name="em_weixinhao">{keyword}</label>'
    myvalue = re.search(abc, content, re.IGNORECASE)
    if myvalue == None:
        # 丢弃# print(f'丢弃{keyword}')
        return False
    else:
        #匹配到微信号# print(f'微信号-------{keyword}')
        return True
#查询关键词，如果有就存到可用list
def matchkeyword(html,keyword):
    if matchwx(html, keyword) or matchGZH(html,keyword):
        print(f"{keyword}存入txt文档ok")
        vip.writetxt(keyword,'符合SEO的词语.txt')
    else:
        print(f"废弃词语{keyword}")
class vipTool():
    #写入文档一行一个
    def writetxt(self,content,txtname):
        try:
            with open(f'{txtname}', 'a+', encoding='utf-8') as f:
                f.write(content + '\n')
        except Exception as e:
            print(e)
            pass

    # 按行读取txt文档的关键词,返回txt列表
    def readtxt(self,txtname):
        wordlist = []
        try:
            for line in open(f'{txtname}', encoding='utf-8'):
                wordlist.append(line.strip())
        except Exception as e:
            print(e)
            pass
        return wordlist

    def writejson(self,dict,jsonname):
        try:
            with open(f"{jsonname}", "w+")as f:  # 写入json文件
                f.write(json.dumps(dict))
                f.close()
        except Exception as e:
            print(e)
            pass

    def readjson(self,jsonname):
        with open(f"{jsonname}", "r")as f:
            cookies = json.loads(f.readline())
        return cookies

    def get_cookies(self):
        """
        使用selenium获取cookies的值，将其存在文件中
        """
        url = 'https://v.sogou.com/v?ie=utf8&query=&p=40030600'
        headers = {'User-Agent': ua}
        html = requests.get(url=url, headers=headers, allow_redirects=False)
        cookies = html.cookies.get_dict()
        print(f"LOG--def get_cookies()--['请求的cookie'],{html.cookies.get_dict()}")
        self.writejson(html.cookies.get_dict(),'cookie.json')
        print("wx_cookies获取成功")

    def checkcookie_useful(self):
        """
        判断cookies是否过期，若过期会自动登录获取cookies
        :return:
        """
        file = os.path.isfile("wx_cookie.json")
        if not file:
            self.get_cookies()
        session = self.get_req()
        url = "https://weixin.sogou.com/weixin?usip=&query=%E9%98%BF%E5%B0%94%E6%B3%95%E7%8B%97&ft=&tsn=1&et=&interation=&type=2&wxid=&page=3&ie=utf8"
        response = session.get(url, allow_redirects=False)
        logger.info("验证cookies是否可用")
        login_state = True
        if response.status_code == 302:
            login_state = False
        if login_state:
            logger.info("cookies可用")
            return session
        else:
            logger.info("cookies不可用，重新获取cookies")
            self.get_cookies()
            session = self.get_req()
            return session

    def random_steep(self):
        """
        防止封号，随机暂停
        :return:
        """
        a = random.randint(2, 8)
        logger.info("暂停{}秒".format(a))
        time.sleep(a)

    def get_req(self):
        """
        建立请求连接，session建立
        :return:
        """
        save_cookies = self.readjson('cookie.json')
        snuid = save_cookies["SNUID"]
        cookie = "ABTEST=2|1561358499|v1; IPLOC=CN1100; SUID=1A4FC17C4631990A000000005D1070A3; SUV=00CDEE0D7CC14F1A5D1070A35DFF7862; SUID=1A4FC17C2113940A000000005D1070A3; weixinIndexVisited=1; pgv_pvi=2997798912; ld=tZllllllll2N9tTHlllllV1S8k7lllllKGV5pklllltlllllpylll5@@@@@@@@@@; LSTMV=682%2C416; LCLKINT=8742; SNUID={}; sct=14; JSESSIONID=aaaoA1hhCs7Mf8ji7bsTw".format(
            snuid)
        header["Cookie"] = cookie
        header["User-Agent"] = ua
        session = requests.Session()
        session.headers = header
        return session

if __name__ == '__main__':
    # 初始化
    keywordsList = vipTool().readtxt('keywords.txt')
    for keyword in keywordsList:
        vip = vipTool()
        session = vip.checkcookie_useful()
        url = f'https://weixin.sogou.com/weixin?type=1&s_from=input&query={keyword}&ie=utf8&_sug_=n&_sug_type_='
        html = session.get(url,allow_redirects=False)
        html.encoding = 'utf-8'
        print(session.headers['Cookie'])
        if html.status_code == 302:
            print("验证码 需要跟换ip")
        vip.random_steep()
        matchkeyword(html.text,keyword)
